package com.zhhy.tool.utils;

import cn.hutool.core.date.DateUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUploadUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.UUID;

/**
 * 生成二维码
 *
 * @author Tellsea
 * @date 2020/10/25
 */
public class QrCodeGeneratorUtils {

    /**
     * 文件上传的保存路径
     */
    public static String UPLOAD_PATH = System.getProperty("user.dir") + File.separator + "upload" + File.separator;

    /**
     * 生成二维码，返回相对路径
     *
     * @param text
     * @return
     */
    public static String generateQRCodeImage(String text) {
        HashMap hashMap = new HashMap(16);
        // 设置二维码字符编码
        hashMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 设置二维码纠错等级
        hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 设置二维码边距
        hashMap.put(EncodeHintType.MARGIN, 1);
        try {
            // 开始生成二维码
            BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, 300, 300, hashMap);

            String fileName = UUID.randomUUID() + ".png";
            String tempPath = "code" + File.separator + DateUtil.today() + File.separator;
            String targetPath = UPLOAD_PATH + tempPath;
			String uploadPath = RuoYiConfig.getUploadPath();
			File fileDir = new File(uploadPath);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
			File file = new File(uploadPath + fileName);
			Path path = file.toPath();

			// 导出到指定目录
            MatrixToImageWriter.writeToPath(bitMatrix, "png", path);
			FileItem fileItem = createFileItem(file);
			MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
			String pathFileName = FileUploadUtils.upload(uploadPath,multipartFile);
			return pathFileName;
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

	private static FileItem createFileItem(File file) {
		FileItemFactory factory = new DiskFileItemFactory(16, null);
		FileItem item = factory.createItem("textField", "text/plain", true, file.getName());
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		try {
			FileInputStream fis = new FileInputStream(file);
			OutputStream os = item.getOutputStream();
			while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return item;
	}

    public static void main(String[] args) {
//		String text = "http://localhost:8081/spotorder-app-user/#/pages/login/login?state=2&storeId=1";
		String text = "https://spotorder.gzzhhy.cn/spotorder-app-user/#/pages/login/login?state=2&storeId=1";
        System.out.println(QrCodeGeneratorUtils.generateQRCodeImage(text));
    }
}
